import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { getReqMainInfo } from '.';

@Catch(HttpException)
export class UinifyExceptionFilter implements ExceptionFilter {
  @Inject(WINSTON_MODULE_PROVIDER)
  private readonly logger: Logger;

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse();
    const req = ctx.getRequest();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const response = exception.getResponse();
    let msg =
      exception.message || (status > 500 ? 'Server Error' : 'Client Error');
    if (
      Object.prototype.toString.call(response) === '[object Object]' &&
      (response as Record<string, any>).message
    ) {
      msg = (response as Record<string, any>).message;
    }

    this.logger.error(msg, {
      status,
      req: getReqMainInfo(req),
    });
    res.status(status >= 500 ? status : 200).json({ code: 1, msg });
  }
}
